package dbms.ypr;

import dbms.ypr.user.DataBasePermissions;
import dbms.ypr.user.TablePermissions;
import dbms.ypr.user.User;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


//以create开头的sql命令
public class Create {
    private static String tName = "";

    public static void createSql(String sql){

        if(sql.contains(" database ")){
            System.out.println("create语句识别成功");
            String dbName = sql.substring(16, sql.length()-1);
            User loginUser = User.getLoginUser(dbms.ypr.SQLConstant.currentUsername);
            if(loginUser.getDataBasePermissions() != null
                    && loginUser.getDataBasePermissions().size() > 0){
                loginUser.getDataBasePermissions().add(new DataBasePermissions(dbName));
            }else {
                loginUser.setDataBasePermissions(new ArrayList<>(Collections.singletonList(new DataBasePermissions(dbName))));
            }
            User.updateUser(loginUser);
            createDir(dbName);
        }
        else if(sql.contains(" table ")){
            System.out.println("create语句识别成功");
            //System.out.println(tName);
            if(dbms.ypr.Utils.bracketMatch(sql)) {
                createTable(sql);
            }
        }
        else if (sql.contains(" view ")){
            createView(sql);
        }
        else {
            System.out.println("ERROR: 语句有错误");
            dbms.ypr.Input.get();
        }

    }

    //创建文件夹
    private static void createDir(String dbName){
        File file = new File(dbms.ypr.SQLConstant.getPath() + "\\" + dbName);
        if(!file.exists()){
            file.mkdir();
            System.out.println("Query OK");
            dbms.ypr.Input.get();
        }
        else{
            System.out.println("ERROR: database exists");
            dbms.ypr.Input.get();
        }
    }

    //创建表格的方法,使用txt文件存储表
    private static void createTable(String sql){
        String tablePath = dbms.ypr.SQLConstant.getNowPath();
        if(null == dbms.ypr.SQLConstant.currentDatabase){
            System.out.println("ERROR: 语句错误,未指定数据库");
            dbms.ypr.Input.get();
            return;
        }
        int index = sql.indexOf("(");
        if(index != -1){
            //System.out.println(index);
            List<String> tableNames = new ArrayList<String>();
            Pattern compile = Pattern.compile("\\s+table\\s+(\\w+)", Pattern.CASE_INSENSITIVE);
            Matcher m = compile.matcher(sql);
            while (m.find()) {
                tableNames.add(m.group());
            }
            if (tableNames.size() == 0) {
                System.out.println("ERROR: 语句错误");
                dbms.ypr.Input.get();
                return;
            }
            tableNames = tableNames.stream().map(String::trim).collect(Collectors.toList());
            tName = tableNames.get(0).split(" ")[1];
            tName = tName.trim();
            User loginUser = User.getLoginUser(dbms.ypr.SQLConstant.currentUsername);
            if(loginUser.getTablePermissions() != null
                    && loginUser.getTablePermissions().size() > 0){
                loginUser.getTablePermissions().add(new TablePermissions(tName));
            }else {
                loginUser.setTablePermissions(new ArrayList<>(Collections.singletonList(new TablePermissions(tName))));
            }
            User.updateUser(loginUser);
            tName += ".txt";
            System.out.println("创建表格方法已经执行");


            File table = new File(tablePath, tName);
            if (!table.exists()) {
                try {
                    table.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String sep = dbms.ypr.SQLConstant.getSeparate();
                //System.out.println(sql);
                String str = sql.replaceAll(sep + "", sep + sep);
                //System.out.println(str);

                Pattern pattern = Pattern.compile("\\(.*\\)");
                Matcher matcher = pattern.matcher(sql);
                String s = "";
                if (matcher.find()) {
                    s = matcher.group(0);
                    //System.out.println(s);
                }

                String s1 = s.substring(1, s.length() - 1);
                //System.out.println(s1);
                String[] strings = s1.split(",");

                List<String> list1 = new ArrayList<>();
                List<String> list2 = new ArrayList<>();
                List<String> list3 = new ArrayList<>();

                for(String s2: strings){
                    String s3 = s2.trim();
                    String[] strings1 = s3.split(" ");
                    list1.add(strings1[0]);
                    list2.add(strings1[1]);
                    for(int i = 2; i < strings1.length; i++){
                        //list3.add(strings1[i]);
                        if(strings1[i].equals("not") && strings1[i+1].equals("null")){
                            list3.add("not null");
                            i++;
                        }
                        else{
                            list3.add(strings1[i]);
                        }
                    }
                    //System.out.println(s3);
                }

                writeFile(list1);
                writeFile(list2);
                writeFile(list3);
                System.out.println("Query OK");
            }
            else{
                System.out.println("ERROR: 该表已经存在");
            }
        }
        else{
            System.out.println("ERROR: 语句有错误");
        }

        dbms.ypr.Input.get();
    }

    //创建视图
    private static void createView(String sql) {
        String tablePath = dbms.ypr.SQLConstant.getNowPath();
        if(null == dbms.ypr.SQLConstant.currentDatabase){
            System.out.println("ERROR: 语句错误,未指定数据库");
            dbms.ypr.Input.get();
            return;
        }

        List<String> tableNames = new ArrayList<String>();
        Matcher m = Pattern.compile("\\s+view\\s+(\\w+)", Pattern.CASE_INSENSITIVE).matcher(sql);
        while (m.find()) {
            tableNames.add(m.group());
        }
        if (tableNames.size() == 0) {
            System.out.println("ERROR: 语句错误");
            dbms.ypr.Input.get();
            return;
        }
        tableNames = tableNames.stream().map(String::trim).collect(Collectors.toList());
        tName = tableNames.get(0).split(" ")[1];
        tName = tName.trim();
        User loginUser = User.getLoginUser(dbms.ypr.SQLConstant.currentUsername);
        if(loginUser.getTablePermissions() !=null
                && loginUser.getTablePermissions().size() > 0){
            loginUser.getTablePermissions().add(new TablePermissions(tName));
        }else {
            loginUser.setTablePermissions(new ArrayList<>(Collections.singletonList(new TablePermissions(tName))));
        }
        User.updateUser(loginUser);
        tName += ".txt";
        System.out.println("创建视图方法已经执行");


        File table = new File(tablePath, tName);
        if (!table.exists()) {
            try {
                table.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            String sep = dbms.ypr.SQLConstant.getSeparate();
            //System.out.println(sql);
            String str = sql.replaceAll(sep + "", sep + sep);
            //System.out.println(str);

            Pattern pattern = Pattern.compile("as\\s+(.*?);");
            Matcher matcher = pattern.matcher(sql);
            String s = "";
            if (matcher.find()) {
                s = matcher.group(0);
                System.out.println(s);
            }
            s = s.substring(s.indexOf("as ")+3);
            writeFile(Collections.singletonList(s));
        }
        else{
            System.out.println("ERROR: 该视图已经存在");
        }

        dbms.ypr.Input.get();
    }

    //将字符串写入文件，list需要写入的字符串列表
    private static void writeFile(List<String> list){

        String str = "";
        //System.out.println(str);

        String sep = dbms.ypr.SQLConstant.getSeparate();

        String path = dbms.ypr.SQLConstant.getNowPath();
        String nowPath = path + "\\" + tName;

        for(String s1: list){

            str += s1 + sep;
        }

        try{
            FileOutputStream fos = new FileOutputStream(
                    new File(nowPath), true);
            str += "\r\n";
            fos.write(str.getBytes());
            fos.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
